﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;

/// <summary>
/// 对于目录的扩展
/// </summary>
public static class DirectoryExtend
{
    /// <summary>
    /// 递归遍历目录及其子目录内的所有文件
    /// </summary>
    /// <param name="dirPath">目录</param>
    /// <param name="action"></param>
    /// <param name="extension">扩展名，如 .xlsx</param>
    public static void ForEachFile(string dirPath, Action<string> action, params string[] extension)
    {
        if (!Directory.Exists(dirPath)) return;

        //如果没有给扩展名，则默认我全都要
        if (extension.Length <= 0) extension = new string[] { "" };

        //遍历本目录下的所有文件
        foreach (var item in extension)
        {
            string[] files = Directory.GetFiles(dirPath, "*" + item);
            if (files == null || files.Length <= 0) continue;//如果这个目录底下没有文件，就跳过
            files.ForEach(s => action?.Invoke(s));
        }

        //遍历本目录下的所有子目录
        foreach (var item in Directory.GetDirectories(dirPath))
        {
            ForEachFile(item, action, extension);
        }
    }

    /// <summary>
    /// 递归遍历目录及其子目录内的所有文件
    /// </summary>
    /// <param name="dirPath"></param>
    /// <param name="action"></param>
    /// <param name="extension">扩展名，如 .xlsx</param>
    public static void ForEachFile(this DirectoryInfo dirPath, Action<string> action, params string[] extension)
    {
        ForEachFile(dirPath.Name, action, extension);
    }
}

